﻿/* System.Compute: a Computation Framework for .NET/Mono
 * Copyright (C) 2011 Ralf "raboni" Boeckhorst
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 */

using System;
using System.Compute.OpenCL;
using System.Drawing;
using System.IO;
using System.Diagnostics;

namespace Usage
{
    class Run
    {
        static void Main(string[] args)
        {
            Platform[] platforms = Platform.GetPlatforms();
            Device[] devices = Device.GetDevices(platforms[0], DeviceType.CPU);
            Context context = new Context(platforms[0], devices);

            DeviceBuffer buffer = new DeviceBuffer(context, MemoryFlags.ReadWrite, sizeof(int) * 256 * 256);

            string source = File.ReadAllText(@".\source.ocl");
            Program prog = new Program(context, source);
            prog.Build(null, devices);

            Kernel kernel = new Kernel(prog, "Test");
            kernel.SetArgument(0, buffer);

            CommandQueue queue = new CommandQueue(context, devices[0], CommandQueueProperties.ProfilingEnable);

            Event evt = queue.EnqueueNDRangeKernel(kernel, 2, null, new SizeT[] { 256, 256 }, null);

            int[,] res = new int[256, 256];
            Event evt2 = queue.EnqueueReadBuffer(buffer, false, 0, sizeof(int) * 256 * 256, ref res, evt);

            evt2.Wait();

            Bitmap bmp = new Bitmap(256, 256);
            for (int y = 0; y < 256; y++)
                for (int x = 0; x < 256; x++)
                    bmp.SetPixel(x, y, Color.FromArgb(res[y, x]));
            bmp.Save("result.png");

            SizeT resolution = devices[0].ProfilingTimerResolution;
            Console.WriteLine(Event.ElapsedSeconds(resolution, evt.CommandStart, evt2.CommandEnd) + " sec");

            Console.WriteLine("press any key to continue...");
            Console.ReadKey();
        }
    }
}
